package com.example.hxds.common.config.xss;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HtmlUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.nio.charset.Charset;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @BelongsProject: hxds
 * @BelongsPackage: com.example.hxds.common.config.xss
 * @Author: caohaoran
 * @CreateTime: 2025-10-16  22:17
 * @Description: TODO
 * @Version: 1.0
 */
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
    public XssHttpServletRequestWrapper(HttpServletRequest request){
        super(request);
    }

    @Override
    //获取的是：URL查询字符串 或 表单数据
    public String getParameter(String name) {
        String value = super.getParameter(name);
        if(!StrUtil.hasEmpty(value)){
            value = HtmlUtil.cleanHtmlTag(value);
        }
        return value;
    }

    @Override
    //获取的是：同名参数的多个值,或者表单中的多选框。
    public String[] getParameterValues(String name) {
        String[] values = super.getParameterValues(name);
        if(values != null){
            for (int i = 0; i < values.length; i++) {
                String value = values[i];
                if(!StrUtil.hasEmpty(value)){
                    value = HtmlUtil.cleanHtmlTag(value);
                }
                values[i] = value;
            }
        }
        return values;
    }

    @Override
    //获取的是：所有参数的映射表,包含所有通过URL或表单提交的参数。
    public Map<String, String[]> getParameterMap() {
        Map<String, String[]> parameters = super.getParameterMap();
        LinkedHashMap<String, String[]> map = new LinkedHashMap<>();
        if(!parameters.isEmpty()){
            for (String key : parameters.keySet()) {
                String[] values = parameters.get(key);
                for (int i = 0; i < values.length; i++) {
                    String value = values[i];
                    if(!StrUtil.hasEmpty(value)){
                        value = HtmlUtil.cleanHtmlTag(value);
                    }
                    values[i] = value;
                }
                map.put(key, values);
            }
        }
        return map;
    }

    @Override
    //获取的是：HTTP请求头的值
    public String getHeader(String name) {
        String value = super.getHeader(name);
        if(!StrUtil.hasEmpty(value)){
            value = HtmlUtil.cleanHtmlTag(value);
        }
        return value;
    }

    @Override
    //获取的是：请求体内容（原始字节流）
    public ServletInputStream getInputStream() throws IOException {
        //获取原始输入流
        InputStream in = super.getInputStream();
        //创建InputStreamReader,指定字符集为UTF-8 将原始的字节流（InputStream）转换为字符流（Reader）
        InputStreamReader reader = new InputStreamReader(in, Charset.forName("UTF-8"));
        //使用BufferedReader包装InputStreamReader,提高读取效率
        BufferedReader buffer = new BufferedReader(reader);
        //使用StringBuffer拼接请求体内容
        StringBuffer body = new StringBuffer();
        String line = buffer.readLine();
        //逐行读取请求体内容，直到读取完所有请求行
        while (line != null){
            body.append(line);
            //BufferedReader的readerLine()方法内部维护一个指针记录当前读取位置，每次调用都会自动移动到下一行的起始位置，因此不需要手动控制指针移动。
            line = buffer.readLine();
        }
        //关闭资源
        buffer.close();
        reader.close();
        in.close();
        Map<String,Object> map = JSONUtil.parseObj(body.toString());
        Map<String,Object> result = new LinkedHashMap<>();
        for (String key : map.keySet()){
            Object val = map.get(key);
            if (val instanceof String){
                if (!StrUtil.hasEmpty(val.toString())){
                    result.put(key, HtmlUtil.cleanHtmlTag(val.toString()));
                }
            }
            else {
                result.put(key, val);
            }
        }
        String json = JSONUtil.toJsonStr(result);
        ByteArrayInputStream bain = new ByteArrayInputStream(json.getBytes());
        return new ServletInputStream() {
            @Override
            public int read() throws IOException {
                return bain.read();
            }

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }
        };
    }
}
